package com.xiangyi.teachingsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.xiangyi.teachingsystem.entity.po.User;
import com.xiangyi.teachingsystem.entity.vo.Result;
import com.xiangyi.teachingsystem.service.UserService;
import com.xiangyi.teachingsystem.validation.groups.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
public class UserController {
    @Autowired
    UserService userService;

    @PostMapping("/updateMsg")
    public Result updateMsg(@Validated(UserInfo.class) @RequestBody User user) {
        User userInfobyId = userService.getById(user.getId());
        if (!Objects.equals(userInfobyId.getJobNum(), user.getJobNum())) {
            User userInfoByJobNum = userService.getOne(new QueryWrapper<User>().eq("job_num", user.getJobNum()));
            if (userInfoByJobNum!=null)
                return Result.failure("学号已存在,请再次确认");
        }


        try {
            userService.updateById(user);
            return Result.success("信息更新成功").setData(user);
        } catch (Exception e) {
            return Result.failure("服务器错误");
        }
    }

    @GetMapping("/userInfoById")
    public Result userInfoById(@RequestParam Integer id){
        try {
            User userInfo = userService.getById(id);
            return Result.success("用户信息查询成功").setData(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器错误").setData(e.getMessage());
        }
    }

    @GetMapping("/userInfoByPhoneNum")
    public Result userInfoByPhoneNum(@RequestParam String phoneNum){
        try {
            User userInfo = userService.getOne(new QueryWrapper<User>()
                    .eq("phone_num",phoneNum));
            if (userInfo==null)
                return Result.failure("手机号不存在");
            return Result.success("用户信息查询成功").setData(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器错误").setData(e.getMessage());
        }
    }

    @GetMapping("/userInfoByjobNum")
    public Result userInfoByjobNum(@RequestParam String jobNum){
        try {
            User userInfo = userService.getOne(new QueryWrapper<User>()
                    .eq("job_num",jobNum));
            if (userInfo==null)
                return Result.failure("手机号不存在");
            return Result.success("用户信息查询成功").setData(userInfo);
        }catch (Exception e){
            e.printStackTrace();
            return Result.failure("服务器错误").setData(e.getMessage());
        }
    }
}
